package com.line.myprojectservice.chatserver.handler;


import cn.hutool.json.JSONObject;
import com.line.myprojectservice.chatserver.constant.Constants;
import com.line.myprojectservice.chatserver.pojo.WebSocketClient;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import static com.line.myprojectservice.chatserver.service.PublicService.*;


/**
 * @author Line
 */
@Slf4j
@ChannelHandler.Sharable
public class DoctorHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private final String departmentName;
    private final String userId;

    public DoctorHandler(String departmentName, String userId) {
        super();
        this.departmentName = departmentName;
        this.userId = userId;
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {

        if (evt.equals(Constants.FIRST_SOCKET)) {
            // 装配一个医生自身实例
            WebSocketClient doctorClient = new WebSocketClient();
            doctorClient.setUserId(userId);
            doctorClient.setChannel(ctx.channel());
            doctorClient.setIdentity("医生");

            //加入总链接map
            allConnectedMap.put(userId, doctorClient);

            //如果这是第一次实例加载，则初始化departmentMap
            initDepartment();

            //加入挂号map
            doctorsMap.get(departmentName).offer(doctorClient);

            log.info("有新医生加入，userId={}, 当前在线人数为：{}", userId, allConnectedMap.size());

            //重新调度
            dispatch(departmentName);
        }
    }



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {

        log.info("进入医生处理链");

        try {
            log.info("userId={}的消息:{}", userId, msg.text());

            JSONObject jsonObject = new JSONObject();
            jsonObject.set("message", msg.text());

            forwardToPatient(userId, jsonObject.toString());
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

        //发生异常时候调用关闭错误连接
        channelInactive(ctx);

        log.error("发生错误");
        cause.printStackTrace();
    }


    /**
     * channelActive 只有当 Channel 变为活动状态,就TCP而言,这意味着连接建立时,
     * 如果添加 ChannelHandler 连接通道后,它将不再看到活动事件。
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {

    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) {

        //总连接不要动，留给心跳服务管理
//        //断开服务器连接
//        allConnectedMap.remove(userId);

        //断开医患连接
        release(departmentName, userId);

        log.info("有一连接关闭，userId={} , 当前在线人数为：{}", userId, allConnectedMap.size());

    }

}

